package com.example.demo6.service;

/**
 * @Author: Lizhi
 * @Date:Create：in 2023/12/5 9:47
 */
import com.example.demo6.dao.GoodsDao;
import com.example.demo6.entity.Goods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class GoodsService implements GoodsDao{
    @Autowired
    private final JdbcTemplate jdbcTemplate;

    public GoodsService(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public int add(Goods goods) {
        String sql = "insert into goods values(null,?,?,?,?,?,0)";
        // 2 调用方法实现
        Object[] args = {goods.getName(),goods.getPrice(),goods.getQuantity(),goods.getCategory(),goods.getSupplier()};
        return jdbcTemplate.update(sql, args);
    }

    @Override
    public int delete(Goods goods) {
        String sql="delete from goods where Id=?";
        Object[] args={goods.getId()};
        return jdbcTemplate.update(sql, args);
    }

    @Override
    public int updata(Goods goods) {
        String sql="update goods set name=?,price=?,quantity=?,category=?,supplier=? where Id=?";
        Object[] args={
                goods.getName(),goods.getPrice(),goods.getQuantity(),goods.getCategory(),goods.getSupplier(),goods.getId()
        };
        return jdbcTemplate.update(sql, args);

    }

    @Override
    public Goods findone(Goods goods) {
        String sql = "select * from goods where Id="+goods.getId().toString();
        return jdbcTemplate.queryForObject(sql,new BeanPropertyRowMapper<Goods>(Goods.class));

    }


//    @Override
//    public Goods findone(Goods goods) {
//        Goods goods1 =new Goods();
//        goods1.setName("orange");
//        goods1.setNumber(100);
//        goods1.setPrice(10);
//        goods1.setSupplier("chongqin");
//        return goods1;
//    }

    @Override
    public List<Goods> findAll(){
        String sql ="select * from goods";
        return jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(Goods.class));
    }
}
